package com.egoo.ticket.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.CustomFieldDao;
import com.egoo.ticket.server.dao.FormTemplateDao;
import com.egoo.ticket.server.pojo.dto.CustomFieldInputDto;
import com.egoo.ticket.server.pojo.dto.CustomFieldOutDto;
import com.egoo.ticket.server.pojo.dto.PageOutputDto;
import com.egoo.ticket.server.pojo.dto.SelectByNameAndTypeDto;
import com.egoo.ticket.server.pojo.entity.CustomField;
import com.egoo.ticket.server.pojo.vo.InteractiveDataVo;
import com.egoo.ticket.server.service.CustomFieldService;
import com.egoo.ticket.server.service.WorkOrderTypeNodeService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Donny_dong
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/customField", produces = "application/json")
@Api(value = "自定义字段管理", tags = "自定义字段", description = "自定义字段管理")
public class CustomfieldController {

    @Autowired
    private CustomFieldService customFieldService;
    @Autowired
    private WorkOrderTypeNodeService workOrderTypeNodeService;
    @Autowired
    private FormTemplateDao formTemplateDao;
    @Autowired
    private CustomFieldDao customFieldDao;

    @ApiOperation(value = "获取所有的自定义字段", notes = "获取所有的自定义字段")
    @RequestMapping(method = RequestMethod.GET, value = "/selectAll")
    public DbResponse selectAll(@ApiParam(value = "当前页", required = true) @RequestParam("currentPage") Integer currentPage,
                                @ApiParam(value = "每页行数", required = true) @RequestParam("pageSize") Integer pageSize, HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        PageOutputDto pageOutputDto = customFieldService.selectAll(currentPage, pageSize, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(pageOutputDto);
        return dbResponse;
    }

    @ApiOperation(value = "获取所有启用的自定义字段", notes = "获取所有启用的自定义字段")
    @RequestMapping(method = RequestMethod.GET, value = "/selectAllOpen")
    public DbResponse selectAllOpen(HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        CustomFieldOutDto customFieldOutDto = customFieldService.selectAllOpen(tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(customFieldOutDto);
        return dbResponse;
    }

    @ApiOperation(value = "获取自定义字段的所有类型", notes = "获取所有自定义字段的所有类型类型")
    @RequestMapping(method = RequestMethod.GET, value = "/selectAllType")
    public DbResponse selectAllType(HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        dbResponse.setRetCode(200);
        dbResponse.setData(customFieldService.selectAllType(tenantId));
        return dbResponse;
    }

    @ApiOperation(value = "根据id获取自定义字段的属性", notes = "根据id获取自定义字段的属性")
    @RequestMapping(method = RequestMethod.GET, value = "/selectContentById")
    public DbResponse selectContentById(@ApiParam(value = "id", required = true) @RequestParam(name = "id") Integer id,
                                        HttpServletRequest request) {
        JSONObject content = customFieldService.selectContentById(id);
        return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "成功", content);
    }

    @ApiOperation(value = "新建自定义字段", notes = "新建自定义字段")
    @RequestMapping(method = RequestMethod.POST, value = "/createCustomfield")
    public DbResponse createCustomfield(@ApiParam(value = "customField", required = true)
                                        @RequestBody CustomFieldInputDto customFieldInputDto, HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "新建失败");
        JSONObject json = customFieldInputDto.getContent();
        JSONArray list = json.getJSONArray("list");
        if (list == null || list.size() < 1) {
            dbResponse.setMsg("新建自定义字段的内容不能为空");
            return dbResponse;
        } else {
            for (int i = 0; i < list.size(); i++) {
                JSONObject data = list.getJSONObject(i);
                String name = data.getString("name");
                String dataSign = data.getString("dataSign");
                if (StringUtils.isBlank(name) || null == name) {
                    dbResponse.setMsg("自定义字段名字不能为空");
                    return dbResponse;
                } else {
                    if (name.length() > ConstantCode.ControllerStrLengthCheck.LENGTH) {
                        dbResponse.setMsg("自定义字段名字超过80个字");
                        return dbResponse;
                    }
					Map<String, String> map = new HashMap<>();
                    map.put("name",name);
                    map.put("tenantId",tenantId);
					List<CustomField> customFields = customFieldDao.selectByMap(map);
                    if (!CollectionUtils.isEmpty(customFields)) {
                        dbResponse.setMsg("该自定义字段已存在");
                        return dbResponse;
                    }
                }
                //自定义字段标识校验
                if (!StringUtils.isEmpty(dataSign)) {
                    CustomField customField = customFieldDao.selectByCode(dataSign, tenantId);
                    if (Objects.nonNull(customField)) {
                        return new DbResponse(ResponseConstant.RES_FAIL_CODE, "自定义字段标识已存在");
                    }
                }


//				if (StringUtils.isEmpty(dataSign)) {
//					return new DbResponse(ResponseConstant.RES_FAIL_CODE,"自定义字段标识不能为空");
//				}else {
//					CustomField customField = customFieldDao.selectByCode(dataSign, tenantId);
//					if (Objects.nonNull(customField)){
//						return new DbResponse(ResponseConstant.RES_FAIL_CODE,"自定义字段标识已存在");
//					}
//				}
            }
        }
        customFieldInputDto.setTenantId(tenantId);
        int retCode = customFieldService.insertByBatch(customFieldInputDto);

		dbResponse.setRetCode(200);
		dbResponse.setMsg("新建成功");

        return dbResponse;
    }

    @ApiOperation(value = "根据字段名称获取自定义字段信息", notes = "根据字段名称获取自定义字段信息")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByName")
    public DbResponse selectByName(@ApiParam(value = "name", required = false) @RequestParam("name") String name, HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<CustomField> customField = customFieldService.selectByName(name, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(customField);
        return dbResponse;
    }


    @ApiOperation(value = "根据字段类型获取自定义字段信息", notes = "根据字段类型获取自定义字段信息")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByType")
    public DbResponse selectByType(@ApiParam(value = "type", required = true) @RequestParam("type") String type, HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<CustomField> customField = customFieldService.selectByType(type, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(customField);
        return dbResponse;
    }

    @ApiOperation(value = "根据字段名称和类型获取自定义字段信息", notes = "根据字段名称和类型获取自定义字段信息")
    @RequestMapping(method = RequestMethod.POST, value = "/selectByNameAndType")
    public DbResponse selectByNameAndType(@ApiParam(value = "selectByNameAndTypeDto", required = true) @RequestBody SelectByNameAndTypeDto selectByNameAndTypeDto,
                                          HttpServletRequest request) {
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        String name = selectByNameAndTypeDto.getName();
        String type = selectByNameAndTypeDto.getType();
        Integer currentPage = selectByNameAndTypeDto.getCurrentPage();
        Integer pageSize = selectByNameAndTypeDto.getPageSize();
        if (pageSize == null || pageSize <= 0) {
            return new DbResponse(ResponseConstant.RES_FAIL_CODE, "pageSize" +
                    "不能为空！");
        }
        if (currentPage == null || currentPage <= 0) {
            return new DbResponse(ResponseConstant.RES_FAIL_CODE, "currentPage" +
                    "不能为空！");
        }
        try {
            return customFieldService.selectByNameAndType(name, type, currentPage, pageSize, tenantId);
        } catch (Exception e) {
            log.info("根据字段名称和类型获取自定义字段信息:" + e);
            return new DbResponse(ResponseConstant.RES_FAIL_CODE,
                    ResponseConstant.SELECT_FAIL_MSG, "根据字段名称和类型获取自定义字段信息:" + e);
        }
    }

    @ApiOperation(value = "更新自定义字段的使用状态", notes = "更新自定义字段的使用状态")
    @RequestMapping(method = RequestMethod.GET, value = "/updateUseStatus")
    public DbResponse updateUseStatus(@ApiParam(value = "id", required = true) @RequestParam(name = "id") Integer id,
                                      @ApiParam(value = "userId", required = true) @RequestParam(name = "userId") String userId,
                                      @ApiParam(value = "useStatus", required = true) @RequestParam(name = "useStatus") Integer useStatus,
                                      HttpServletRequest request) {
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "更新失败");
        CustomField customField = customFieldService.selectById(id);
        if (customField == null) {
            dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
            dbResponse.setMsg("该自定义字段不存在");
            return dbResponse;
        }
        int retCode = customFieldService.updateUseStatus(id, userId, useStatus, tenantId);
        if (retCode == 1) {
            dbResponse.setRetCode(200);
            dbResponse.setMsg("更新成功");
        }
        return dbResponse;
    }

    @ApiOperation(value = "更新自定义字段的属性", notes = "更新自定义字段的属性")
    @RequestMapping(method = RequestMethod.POST, value = "/updateContent")
    public DbResponse updateContent(@ApiParam(value = "customField", required = true) @RequestBody CustomFieldInputDto customFieldInputDto,
                                    HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        String dataSign = customFieldInputDto.getDataSign();
        DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "更新失败");
        Integer id = customFieldInputDto.getId();
        CustomField customField = customFieldService.selectById(id);
        if (customField == null) {
            return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该自定义字段不存在");
        }
//		CustomField selectByCode = customFieldDao.selectByCode(customFieldInputDto.getDataSign(), tenantId);
//        if (!customFieldInputDto.getDataSign().equals(customField.getCode()) && !customField.getId().equals(customFieldInputDto.getId())) {
////            return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该自定义字段的标识已存在");
////        }
        //自定义字段标识校验
        if (!StringUtils.isEmpty(dataSign) && !dataSign.equals(customField.getCode())) {
            if (Objects.nonNull(customFieldDao.selectByCode(dataSign, tenantId))) {
                return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该自定义字段的标识已存在");
            }
        }
        String name = customFieldInputDto.getName();
        if (StringUtils.isBlank(name) || null == name) {
            return new DbResponse(ResponseConstant.RES_FAIL_CODE, "自定义字段名字不能为空");
        } else {
            if (name.length() > ConstantCode.ControllerStrLengthCheck.LENGTH) {
                return new DbResponse(ResponseConstant.RES_FAIL_CODE, "自定义字段名字超过20个字");
            }
			Map<String, String> map = new HashMap<>();
            map.put("name",name);
            map.put("tenantId",tenantId);
			List<CustomField> customFields = customFieldDao.selectByMap(map);
            if (!CollectionUtils.isEmpty(customFields) && !customFields.get(0).getId().equals(id)) {
                dbResponse.setMsg("该名称已存在,更换后重试");
                return dbResponse;
            }

        }
        customFieldInputDto.setTenantId(tenantId);
        Integer retCode = customFieldService.updateContent(customFieldInputDto);
        if (retCode == 1) {
            return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "更新成功");
        }
        return new DbResponse(ResponseConstant.RES_FAIL_CODE, "更新失败");
    }

    @ApiOperation(value = "删除自定义字段", notes = "删除自定义字段")
    @RequestMapping(method = RequestMethod.GET, value = "/delete")
    public DbResponse delete(@ApiParam(value = "id", required = true) @RequestParam(name = "id") Integer id,
                             HttpServletRequest request) {
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        Integer retCode = customFieldService.delete(id, tenantId);
        if (retCode == 1) {
            return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "删除成功");
        }
        return new DbResponse(ResponseConstant.RES_FAIL_CODE, "删除失败");
    }

    @ApiOperation(value = "根据名字模糊搜索工单优先级", notes = "根据名字模糊搜索工单优先级")
    @RequestMapping(method = RequestMethod.GET, value = "/selectWorkOrderPriorityByName")
    public DbResponse selectWorkOrderPriorityByName(@ApiParam(value = "name", required = true) @RequestParam(name = "name") String name,
                                                    HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<InteractiveDataVo> interactiveDataList = customFieldService.selectWorkOrderPriorityByName(name, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveDataList);
        return dbResponse;
    }

    @ApiOperation(value = "根据id获取自定义字段下拉列表数据", notes = "根据id获取自定义字段下拉列表数据")
    @RequestMapping(method = RequestMethod.GET, value =
            "/getAllSelectFieldListById")
    public DbResponse getAllSelectFieldListById(@ApiParam(value = "id", required = true)
                                                @RequestParam(name = "id") Integer id,
                                                HttpServletRequest request) {
        DbResponse dbResponse = new DbResponse();
        List<InteractiveDataVo> interactiveDataList = customFieldService.selectAllSelectFieldListById(id);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveDataList);
        return dbResponse;
    }

    @ApiOperation(value = "根据名字模糊搜索工单来源", notes = "根据名字模糊搜索工单来源")
    @RequestMapping(method = RequestMethod.GET, value = "/selectWorkOrderSourceByName")
    public DbResponse selectWorkOrderSourceByName(@ApiParam(value = "name", required = true) @RequestParam(name = "name") String name,
                                                  HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<InteractiveDataVo> interactiveDataList = customFieldService.selectWorkOrderSourceByName(name, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveDataList);
        return dbResponse;
    }

    @ApiOperation(value = "根据工单类型Id查询节点集合", notes = "根据工单类型Id查询节点集合")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByWorkOrderTypeId")
    public DbResponse selectByWorkOrderTypeId(@ApiParam(value = "workOrderTypeId", required = true) @RequestParam(name = "workOrderTypeId") Long workOrderTypeId,
                                              HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<InteractiveDataVo> interactiveDataList = workOrderTypeNodeService.selectByWorkOrderTypeId(workOrderTypeId, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveDataList);
        return dbResponse;
    }


    @ApiOperation(value = "根据工单类型Id和节点名字模糊搜索工单节点", notes = "根据工单类型Id和节点名字模糊搜索工单节点")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByWorkOrderTypeIdAndNodeName")
    public DbResponse selectByWorkOrderTypeIdAndNodeName(@ApiParam(value = "workOrderTypeId", required = true) @RequestParam(name = "workOrderTypeId") Long workOrderTypeId,
                                                         @ApiParam(value = "workOrderNodeName", required = true) @RequestParam(name = "workOrderNodeName") String workOrderNodeName,
                                                         HttpServletRequest request) {
        String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        DbResponse dbResponse = new DbResponse();
        List<InteractiveDataVo> interactiveDataList = workOrderTypeNodeService.selectByWorkOrderTypeIdAndNodeName(workOrderTypeId, workOrderNodeName, tenantId);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveDataList);
        return dbResponse;
    }

    @ApiOperation(value = "根据节点id获取节点名字", notes = "根据节点id获取节点名字")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByWorkOrderNodeId")
    public DbResponse selectByWorkOrderNodeId(@ApiParam(value = "workOrderNodeId", required = true) @RequestParam(name = "workOrderNodeId") Long workOrderNodeId) {
        DbResponse dbResponse = new DbResponse();
        InteractiveDataVo interactiveData = workOrderTypeNodeService.selectByWorkOrderNodeId(workOrderNodeId);
        dbResponse.setRetCode(200);
        dbResponse.setData(interactiveData);
        return dbResponse;
    }


    @ApiOperation(value = "根据code获取自定义", notes = "根据code获取自定义")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByCode")
    public DbResponse selectByCode(@ApiParam(value = "code", required = true) @RequestParam(name = "code") String code, HttpServletRequest request) {
        String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
        if (StringUtils.isEmpty(code)) {
            return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "该参数无对应数据", new JSONArray());
        }
        JSONArray jsonArray = customFieldService.selectByCode(code, tenantId);
        return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.SELECT_SUCCESS_MSG, jsonArray);
    }
}
